package ro.qwq.webssh.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import ro.qwq.webssh.Utils.EhCacheUtils;
import ro.qwq.webssh.Utils.NetworkUtils;
import ro.qwq.webssh.Utils.SftpUtils;
import ro.qwq.webssh.Utils.WebShellUtils;
import ro.qwq.webssh.entity.WebSSHData;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * RouterController - 请求路由控制器
 * </p>
 *
 * @since 2022/1/5
 * @author JiuyeXD
 * @version 1.0
 */
@Controller
@Log4j2
public class RouterController {

    @GetMapping({"/", "/index"})
    public String index(HttpServletRequest request){
        log.info(NetworkUtils.getIpAddr(request));
        return "index";
    }


    @GetMapping("/sftp")
    public String sftp(String params, Model model) {
        String sessionId = WebShellUtils.getSessionId();
        log.info("sessionId：{}", sessionId);
        WebSSHData sshData = JSON.parseObject(params, WebSSHData.class);
        // 存放ssh连接信息
        if (sshData != null) {
            EhCacheUtils.put(sessionId, sshData);
        } else {
            sshData = EhCacheUtils.get(sessionId);
        }
        if (sshData != null) {
            SftpUtils sftpUtils = new SftpUtils(sshData);
            boolean login = sftpUtils.login();
            // 登录成功状态
            model.addAttribute("login", login);
            model.addAttribute("host", sshData.getHost());
            sftpUtils.logout();
        }
        return "sftp";
    }
}
